import pandas as pd
import numpy as np

def load_data(file_path):
    data = pd.read_csv(file_path, header=None)
    data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']
    return data

def euclidean_distance(point1, point2):
    return np.sqrt(np.sum((point1 - point2) ** 2))

class KNN:
    def __init__(self, k=3):
        self.k = k
        self.x_train = None
        self.y_train = None

    def fit(self, x, y):
        self.x_train = x
        self.y_train = y

    def predict(self, x_test):
        predictions = []
        for test_point in x_test:
            distances = []
            for index, train_point in enumerate(self.x_train):
                distance = euclidean_distance(test_point, train_point)
                distances.append((distance, self.y_train[index]))
            distances.sort(key=lambda x: x[0])  
            neighbors = distances[:self.k]  

            class_votes = {}
            for _, vote in neighbors:
                if vote in class_votes:
                    class_votes[vote] += 1
                else:
                    class_votes[vote] = 1

            predicted_class = max(class_votes.items(), key=lambda x: x[1])[0]
            predictions.append(predicted_class)
        return predictions

if __name__ == '__main__':
    iris_data = load_data('D:\数据挖掘\iris.csv')

    X = iris_data[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']].values
    y = iris_data['class'].values

    split_index = int(len(X) * 0.85)
    X_train, X_test = X[:split_index], X[split_index:]
    y_train, y_test = y[:split_index], y[split_index:]

    knn = KNN(k=3)
    knn.fit(X_train, y_train)

    predictions = knn.predict(X_test)

    accuracy = np.mean(predictions == y_test)
    print("准确率：", accuracy)